import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# 生成模拟数据
np.random.seed(42)
n_samples, n_features = 100, 20
X = np.random.randn(n_samples, n_features)

# 构造稀疏目标变量（只有前3个特征有效）
true_coef = np.zeros(n_features)
true_coef[:3] = [1.5, -2.0, 0.8]
y = X @ true_coef + np.random.normal(0, 0.5, size=n_samples)

# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 拟合Lasso回归模型
lasso = Lasso(alpha=0.1)  # alpha 是正则化强度
lasso.fit(X_train, y_train)

# 输出模型系数
print("Lasso回归系数:")
print(lasso.coef_)

# 模型评估
y_pred = lasso.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f"测试集均方误差: {mse:.4f}")

# 可视化实际值 vs 预测值
plt.scatter(y_test, y_pred)
plt.xlabel("实际值")
plt.ylabel("预测值")
plt.title("Lasso回归：实际值 vs 预测值")
plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--')
plt.grid(True)
plt.show()
